package com.gooluke.netty.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @author gooluke
 * description
 * datetime 2025-05-18 3:56
 */
public class MyServerChannelInboundHandler extends SimpleChannelInboundHandler<String> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        System.out.println("接收到消息：" + s);
        channelHandlerContext.channel().writeAndFlush("【服务端发送】：" + System.currentTimeMillis());
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端建立连接! " + ctx.channel().remoteAddress());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端断开连接! " + ctx.channel().remoteAddress());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 发生异常时（可选：不打印堆栈，仅输出友好提示）
        System.out.println("客户端连接异常: " + cause.getMessage());
        ctx.close(); // 关闭连接
    }
}
